package com.example.controller;

import com.example.mapper.DepartmentMapper;
import com.example.mapper.EmployeeMapper;
import com.example.pojo.Department;
import com.example.pojo.Employe;
import com.example.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    DepartmentMapper departmentMapper;

    @PreAuthorize("hasAnyRole('admin')")
    @RequestMapping("/emps")
    public String queryEmp(Model model){
        List<Employee> employees = employeeMapper.queryEmp();
        System.out.println("Employee:" + employees);
        model.addAttribute("emps", employees);
        return "list";
    }

    @GetMapping("/emp")
    public String toAddEmp(Model model){
        List<Department> departments = departmentMapper.queryDpt();
        model.addAttribute("departments", departments);
        return "add";
    }

    @PostMapping("/emp")
    public String addEmp(Employe employe){
        System.out.println("add:" + employe);
        employeeMapper.addEmp(employe);
        return "redirect:/emps";
    }

    @GetMapping("update/{id}")
    public String toUpdateEmp(@PathVariable("id") int id, Model model){
        List<Department> departments = departmentMapper.queryDpt();
        model.addAttribute("departments", departments);
        Employee employee = employeeMapper.queryEmpById(id);
        model.addAttribute("emp", employee);
        return "update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeMapper.updateEmp(employee);
        return "redirect:/emps";
    }

    @GetMapping("delete/{id}")
    public String deleteEmp(@PathVariable("id") int id){
        employeeMapper.deleteEmp(id);
        return "redirect:/emps";
    }

    //用于初始化数据的时候，进行数据类型转换，把String类型转为Date类型
    @InitBinder
    public void initBinder(WebDataBinder binder){

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
